from datetime import datetime
import time

import numpy as np
from flask import *
from util import *
import json
from flask import *
from flask_sqlalchemy import SQLAlchemy
# 解决python3数据库连接问题
# MySQLdb只支持Python2.*，还不支持3.*   可以用PyMySQL代替。
import pymysql
pymysql.install_as_MySQLdb()
from util.ReslutReturn import *
# from exception_handle.global_exception_handle import *
# from views.CbyUserViews import *
from flask_cors import *
import alg_model.Alg_Run as  Alg_Run

# 指明工程文件，代表当前py文件所在目录为工程目录 __name__ == '__main__'
app = Flask(__name__,static_folder='static',static_url_path='/static',template_folder='templates')

# 跨域解决
CORS(app, supports_credentials=True)
@app.after_request
def cors(environ):
    environ.headers['Access-Control-Allow-Origin']='*'
    environ.headers['Access-Control-Allow-Method']='*'
    environ.headers['Access-Control-Allow-Headers']='x-requested-with,content-type'
    return environ


# 配置对象加载配置信息
class DefaultConfig(object):
    """
    默认配置
    """
    SQLALCHEMY_DATABASE_URI = "数据库URI"
    # 设置这一项是每次请求结束后都会自动提交数据库中的变动
    SQLALCHEMY_COMMIT_ON_TEARDOWN = True

# 设置app配置
# app.config.from_object(DefaultConfig)
app.config.from_pyfile('setting.py')

# 数据库配置
db = SQLAlchemy(app)

def dic2obj(d):
    top = type('new', (object,), d)
    seqs = tuple, list, set, frozenset
    for i, j in d.items():
        if isinstance(j, dict):
            setattr(top, i, byte_obj_decode_dic(j))
        elif isinstance(j, seqs):
            setattr(top, i,
                type(j)(byte_obj_decode_dic(sj) if isinstance(sj, dict) else sj for sj in j))
        else:
            setattr(top, i, j)
    return top
def byte_obj_decode_dic(obj_byte):
    obj_json = str(obj_byte).replace('b\'','\'').replace('Namespace(','{').replace(')','}').replace('=',':').replace('\'','\"')
    dict = json.loads(obj_json)
    return dict
def byte_obj_decode_obj(obj_byte):
    byte_obj_decode_dic(obj_byte)
    return dic2obj(obj_byte)


# 全局异常处理
@app.errorhandler(500)
def errorHandle(e):
    return error("全局异常捕获!")
# 指定异常捕获
@app.errorhandler(ZeroDivisionError)
def zero_error(e):
    return error("除数不能为0!")

@app.get("/python/testDb")
def testDb():
    userList = CbyUser.query.all()
    userDictList = []
    for i in range(len(userList)):
        userDictList.append(userList[i].asDict())
    print(userDictList)
    return ok("查询成功",userDictList)

@app.post("/python/testXGB")
def testXGB():
    # 请求体重包含的data字典
    request_data_dic = json.loads(request.data.decode('utf-8'))
    dateList = request_data_dic["date"]
    dataList = request_data_dic["data"]
    print(len(dateList))
    print(len(dataList))
    dateList, dataList = Alg_Run.testXGB(dateList, dataList)
    return ok("预测成功",{"date":dateList,"data":dataList})

# 创建数据库模型类
class CbyUser(db.Model):
    """
    user表
    """
    __tablename__ = "cby_user"
    id = db.Column(db.String,primary_key=True)
    name = db.Column(db.String)
    nick_name = db.Column(db.String)
    password = db.Column(db.String)
    email = db.Column(db.String)
    phone = db.Column(db.String)
    identity_id = db.Column(db.String)
    detail = db.Column(db.String)
    insert_time = db.Column(db.String)
    update_time = db.Column(db.String)
    def asDict(self):
        return {"id":self.id,"name":self.name,"nick_name":self.nick_name,"password":self.password,"email":self.email,"phone":self.phone,"identity_id":self.identity_id,"detail":self.detail}

class MyEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        elif isinstance(obj, bytes):
            return str(obj, encoding='utf-8')
        else:
            return super(MyEncoder, self).default(obj)


if __name__ == '__main__':
    app.run()
